import { create } from "zustand";
import config from "@/config"; // 确保这里配置路径正确

interface StoreState {
  isLoggedIn: boolean | string;
  userName: string;
  theme: "light" | "dark";
  lang: string;
  login: (name: string) => void;
  logout: () => void;
  logoutFail: () => void;
  setTheme: (theme: "light" | "dark") => void;
  setLanguage: (lang: string) => void;
}

const useStore = create<StoreState>((set) => ({
  isLoggedIn: localStorage.getItem("isLoggedIn") || "", // 从 localStorage 初始化
  userName: localStorage.getItem("userName") || "",
  theme: "light",
  lang: localStorage.getItem("i18nextLng") ?? config.lang,
  login: (name: string) => {
    localStorage.setItem("isLoggedIn", "true"); // 登录时持久化
    localStorage.setItem("userName", name); // 持久化用户名
    set({ isLoggedIn: true, userName: name });
  },
  logout: () => {
    localStorage.removeItem("isLoggedIn"); // 登出时清除持久化
    localStorage.removeItem("userName"); // 清除用户名
    set({ isLoggedIn: false, userName: "" });
  },
  logoutFail: () => {
    localStorage.setItem("isLoggedIn", "error");
    set({ isLoggedIn: "error", userName: "" });
  },
  setTheme: (theme: "light" | "dark") => set({ theme }),
  setLanguage: (lang: string) => {
    localStorage.setItem("i18nextLng", lang); // 保存语言到 localStorage
    set({ lang });
  },
}));

export default useStore;
